<?php
class Zendhlt_Mail_Mail  extends Zend_Mail
{

	static $fromName = "Administrator";

	static $fromEmail = "admin@kenhnhatro.net";

	/**
	 *
	 * @var Zend_View
	 */
	static $_defaultView;

	/**
	 * current instance of our Zend_View
	 * @var Zend_View
	 */
	protected $_view;

	protected static function getDefaultView()
	{
		if(self::$_defaultView === null)
		{
			self::$_defaultView = new Zend_View();
			self::$_defaultView->setScriptPath(APPLICATION_PATH . '/modules/admin/views/scripts/email/template/');
		}
		return self::$_defaultView;
	}

	public function sendHtmlTemplate($template, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE,$transport)
	{
		$html = $this->_view->render($template);
		$this->setBodyHtml($html,$this->getCharset(), $encoding);
		self::buildHtml();
		$this->send($transport);
	}

	public function setViewParam($property, $value)
	{
		$this->_view->__set($property, $value);
		return $this;
	}

	public function __construct($charset = 'UTF-8')
	{
		parent::__construct($charset);
		$this->setFrom(self::$fromEmail, self::$fromName);
		$this->_view = self::getDefaultView();
	}
	public function buildHtml()
	{
		$this->setType(Zend_Mime::MULTIPART_RELATED);
		$matches = array();
		preg_match_all("#<img.*?src=['\"]file://([^'\"]+)#i",
		$this->getBodyHtml(true),
		$matches);
		$matches = array_unique($matches[1]);

		if (count($matches ) > 0) {
			foreach ($matches as $key => $filename) {
				if (is_readable($filename)) {
					$at = $this->createAttachment(file_get_contents($filename));
					$at->type = $this->mimeByExtension($filename);
					$at->disposition = Zend_Mime::DISPOSITION_INLINE;
					$at->encoding = Zend_Mime::ENCODING_BASE64;
					$at->id = 'cid_' . md5_file($filename);
					$this->setBodyHtml(str_replace('file://' . $filename,
                                       'cid:' . $at->id,
					$this->getBodyHtml(true)),
                                       'UTF-8',
					Zend_Mime::ENCODING_8BIT);
				}
			}
		}
	}
	public function mimeByExtension($filename)
	{
		if (is_readable($filename) ) {
			$extension = pathinfo($filename, PATHINFO_EXTENSION);
			switch ($extension) {
				case 'gif':
					$type = 'image/gif';
					break;
				case 'jpg':
				case 'jpeg':
					$type = 'image/jpg';
					break;
				case 'png':
					$type = 'image/png';
					break;
				default:
					$type = 'application/octet-stream';
			}
		}

		return $type;
	}
}